<template>
  <view class="chat">
    <u-navbar
      :is-back="true"
      title-size="36"
      :title="topName"
      :border-bottom="false"
      back-icon-color="#333"
      title-color="#333"
    ></u-navbar>
    <scroll-view
      class="scroll-view"
      :style="{ height: `${windowHeight - inputHeight}px` }"
      id="scrollview"
      scroll-y="true"
      :scroll-top="scrollTop"
      @scrolltoupper="topRefresh"
      @click.stop.prevent="touchClose"
    >
      <view id="msglistview" class="chat-body" @click="touchClose">
        <!-- <u-loading-icon v-if="loading"/> -->
        <view v-for="(item, index) in msgList" :key="index">
          <view class="msg-time" v-if="item.isShowTime">
            {{ changeTime(item.sendTime) }}
          </view>
          <view class="item self" v-if="item.senderId == userId">
            <view
              class="msg-menu menu-right"
              :style="{ display: showBoxId == item.id ? 'block' : 'none' }"
            >
              <view class="tr-icon tr-icon-right"></view>
              <!-- 	<ChatMsgMenu :msgUserId="item.senderId" :msgId="item.id" :content="item.content"
                  :msgSortId="index" :time="item.sendTime" @cancelMsg="cancelMsg" /> -->
            </view>
            <view @longpress="showBoxId = item.id">
              <view class="content-text right" v-if="item.type == 'text'">
                <image
                  v-if="
                    item.content.startsWith('http') &&
                    (item.content.endsWith('.png') ||
                      item.content.endsWith('.jpg') ||
                      item.content.endsWith('.jpeg') ||
                      item.content.endsWith('.webp') ||
                      item.content.endsWith('.gif'))
                  "
                  class="img-style"
                  :src="item.content"
                  mode="widthFix"
                />
                <text v-else>{{ item.content }}</text>
              </view>
              <view class="content-text right" v-else-if="item.type == 'voice'">
                <view style="display: flex" @click="playSound(item.content)">
                  <uni-icons type="mic" size="30"></uni-icons>
                  <!-- <text>{{ item.soundTIme }}</text> -->
                  语音
                  <!-- <image style="width: 42rpx;height: 42rpx;" :src="imgConf.voiceBtn" /> -->
                </view>
              </view>
              <view class="content-img" v-else-if="item.type == 'img'">
                <image class="img-style" :src="item.content" mode="widthFix" :lazy-load="true" />
              </view>
              <view class="content-video" v-else>
                <!-- #ifndef APP -->
                <video class="video-style" :src="item.content" />
                <!-- #endif -->
                <!-- #ifdef APP -->
                <!-- <SubVideo :src="item.content" class="video-style"></SubVideo> -->
                <view
                  @click="playVideo(item)"
                  class="video-style"
                  style="
                    background-color: black;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  <image style="width: 80rpx; height: 80rpx" src="/static/img/bf@2x.png"></image>
                </view>
                <!-- #endif -->
              </view>
            </view>
            <image class="avatar" :src="userAvatar" />
          </view>
          <view class="item Ai" v-else>
            <image class="avatar" :src="item.wxUser.headImg" />
            <view @longpress="showBoxId = item.id">
              <view class="content-text left" v-if="item.type == 'text'">
                {{ item.content }}
              </view>
              <view class="content-text left" v-else-if="item.type == 'voice'">
                <view style="display: flex" @click="playSound(item.content)">
                  <uni-icons type="mic" size="30"></uni-icons>
                  <!-- <text>{{ item.soundTIme }}</text> -->
                  语音
                  <!-- <image style="width: 42rpx;height: 42rpx;" :src="imgConf.voiceBtn" /> -->
                </view>
              </view>
              <view class="content-img" v-else-if="item.type == 'img'">
                <image class="img-style" :src="item.content" mode="widthFix" :lazy-load="true" />
              </view>
              <view class="content-video" v-else>
                <!-- #ifndef APP -->
                <video class="video-style" :src="item.content" />
                <!-- #endif -->

                <!-- #ifdef APP -->
                <!-- <SubVideo :src="item.content" class="video-style"></SubVideo> -->
                <view
                  @click="playVideo(item)"
                  class="video-style"
                  style="
                    background-color: black;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  <image style="width: 80rpx; height: 80rpx" src="/static/img/bf@2x.png"></image>
                </view>
                <!-- #endif -->
              </view>
            </view>
            <view
              class="msg-menu menu-left"
              :style="{ display: showBoxId == item.id ? 'block' : 'none' }"
            >
              <view class="tr-icon tr-icon-left"></view>
              <!-- <ChatMsgMenu :msgUserId="item.senderId" :msgId="item.id" :content="item.content"
                :msgSortId="index" :time="item.sendTime" @cancelMsg="cancelMsg" /> -->
            </view>
          </view>
        </view>
      </view>
      <view class="" style="height: 180rpx"></view>
    </scroll-view>

    <view class="chat-bottom" :style="{ height: `${inputHeight}rpx` }">
      <view class="send-msg" :style="{ bottom: `${keyboardHeight}rpx` }">
        <view class="uni-textarea">
          <image class="icon-style" src="@/static/chat_voice.png" @click="changeInputType" />
          <view class="out_textarea_box">
            <!-- @focus="isFouce = true"
              @blur="isFouce = false" -->
            <textarea
              placeholder-class="textarea_placeholder"
              :style="{ textAlign: textareaConf.disabled ? 'center' : '' }"
              v-model="chatMsg"
              maxlength="250"
              confirm-type="send"
              auto-height
              :placeholder="textareaConf.text"
              :show-confirm-bar="false"
              :adjust-position="false"
              :disabled="textareaConf.disabled"
              @confirm="handleSend(1)"
              @linechange="sendHeight"
              @focus="focus"
              @blur="blur"
              @touchstart="handleTouchStart"
              @touchmove="handleTouchMove"
              @touchend="handleTouchEnd"
            />
          </view>
          <view class="right fb" style="display: flex" v-if="!chatMsg">
            <image class="icon-style" src="@/static/add.png" @click="moreMenu" />
          </view>
          <view class="sendBtn" v-else @click="handleSend(1)"> 发送 </view>
        </view>
      </view>
      <view :style="{ display: showMoreMenu ? 'block' : 'none' }" class="more-menu">
        <view class="inner-box">
          <view class="menu" @click="sendFile('choose', '')">
            <view>
              <image class="i-style" src="@/static/xj.png"></image>
              <view class="t-style">照片</view>
            </view>
          </view>
          <!-- <view class="menu" @click="sendFile('shoot','')">
            <view>
              <image class="i-style" src="@/static/ps.png"></image>
              <view class="t-style">拍摄</view>
            </view>
          </view> -->
        </view>
      </view>
    </view>
    <view class="voice-mask" v-show="voice.mask">
      <view class="inner-mask">
        <view class="voice-progress-box" :style="{ width: `${progressNum}` + 'rpx' }">
          <view class="third-icon" />
          <view class="progress-num"> {{ voice.length }}s </view>
        </view>
        <view class="cancel-btn" :class="{ cancelBtn: voice.cancel }">
          <!-- <image style="width: 60rpx;height: 60rpx;" src="/static/chat/cancelSend.png"></image> -->
        </view>
        <view class="show-tips"> 上滑取消发送 </view>
        <view class="bottom-area">
          <!-- <image class="img-style" :src="imgConf.voiceBtn" /> -->
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import timeMethod from '../../common/TimeMethod.js' //时间工具类
import { uploadFiles } from '../../common/upload.js'
// #ifdef APP
// import { SubVideo } from "../../components/SubVideo.vue"
import permision from '@/common/permission.js'
// #endif
import { openGoEasyConnect } from '../../common/goeasy.js'

export default {
  // #ifdef APP
  // components: { SubVideo },
  // #endif
  data() {
    return {
      $goEasy: undefined,

      isFouce: false,
      imgConf: {
        //界面icon图片配置，可自定义
        emoji: '/static/img/bq.png',
        more: '/static/img/add.png',
        sendphoto: '/static/chat/photo.png',
        sendVideo: '/static/chat/video.png',
        takePhoto: '/static/chat/video.png',
        voiceBtn: '/static/chat/voice.png',
        keyboard: '/static/chat/keyboard.png',
        speak: '/static/chat/speak.png',
        replayChange: '/static/chat/replay.png',
        replay: '/static/chat/replay.png',
        replaing: '/static/chat/loading.png'
      },
      changeLogUrl: '/static/img/yy.png',
      loading: false,
      keyboardHeight: 0,
      bottomHeight: 0,
      scrollTop: 0,
      chatMsg: '',
      userId: '', //自己的userId
      // userHeadImg: "/static/bg.png", //自己的头像
      toUserId: '', //聊天朋友的userId
      // toUserHeadImg: "", //聊天朋友的头像
      pageSize: 20, //分页数量
      pageNum: 1, //分页开始数
      returnPageNum: '', //接口返回的聊天信息的总页数
      msgList: [], //聊天消息list
      judgeScrollToBottom: true,
      startTime: '',
      msgID: 0,
      showBoxId: '',
      showBoxUserId: '',
      showMoreMenu: false,
      textareaConf: {
        disabled: false,
        text: ''
      },
      voice: {
        //语音录制界面配置
        mask: false, //遮罩层
        length: 0, //语音录制时长
        cancel: false, //是否取消发送
        startX: '', //获取
        startY: '',
        timer: '',
        recordInstance: '', //uni语音录制实例
        finished: false //是否已结束录制
      },
      msgConf: {
        showTimeSpace: 120 //消息隔多长时间才展示
      },
      toId: '',
      status: '',
      supId: '',
      tokeId: '',

      userAvatar: '',
      realName: '',
      userId: '',
      receiveUserInfo: {
        //接收方信息
        realname: '',
        avatar: ''
      },
      toAccountid: '', //接收方id
      im: null,
      senderId: '',
      toShopId: '',
      shopUserId: '',
      topName: '聊天窗口'
    }
  },
  updated() {
    //页面更新时调用聊天消息定位到最底部
    if (this.judgeScrollToBottom) {
      this.scrollToBottom()
    }
  },
  computed: {
    //获取窗口页面高 度
    windowHeight() {
      return uni.getSystemInfoSync().windowHeight
    },

    // 键盘弹起来的高度+发送框高度
    inputHeight() {
      return this.bottomHeight + this.keyboardHeight
    },

    //语音录制时进度条
    progressNum() {
      return this.voice.length * 2 + 250
    }
  },
  onShow() {
    this.$goEasy = openGoEasyConnect()
    this.im = this.$goEasy.im
    const app = this
    this.im.on(this.$goEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, function (message) {
      console.log('=============2=========')
      let wxUser = {
        nickName: app.userName,
        headImg: app.userAvatar
      }
      if (app.senderId != message.senderId) {
        wxUser.nickName = app.receiveUserInfo.realname
        wxUser.headImg = app.receiveUserInfo.avatar
      }
      let text = JSON.parse(message.payload.text)
      app.msgList.push({
        id: message.messageId,
        senderId: message.senderId,
        acceptUserId: message.receiverId,
        type: message.type,
        content: text.content,
        sendTime: message.timestamp,
        wxUser: wxUser
      })
    })
  },
  onHide() {
    this.$goEasy.disconnect()
  },
  onLoad(e) {
    const userInfo = uni.getStorageSync('userInfo') || {}
    this.userId = userInfo.id
    this.userAvatar = userInfo.avatar
    this.realName = userInfo.nickname
    this.senderId = this.userId
    this.toAccountid = e.userId

    if (e.shopId) {
      this.$u.get('/app-api/shop/info/get', { id: e.shopId }).then((res) => {
        this.toShopId = e.shopId
        this.shopUserId = res.data.userId
        //本人是商家
        if (this.senderId == this.shopUserId) {
          this.userAvatar = res.data.logo
          this.realName = res.data.name
          this.$u.get('/app-api/member/user/get-simple', { userId: e.userId }).then((res) => {
            this.receiveUserInfo.realname = res.data.nickname
            this.receiveUserInfo.avatar = res.data.avatar
            this.topName = '聊天消息:(' + res.data.nickname + ')'
            this.getMessage()
          })
        }
        //本人非商家，对方是商家
        else {
          this.topName = res.data.name
          this.receiveUserInfo.realname = res.data.name
          this.receiveUserInfo.avatar = res.data.logo
          this.getMessage()
        }
        // console.log('=============1=========')
      })
    } else {
      this.$u.get('/app-api/member/user/get-simple', { userId: e.userId }).then((res) => {
        this.receiveUserInfo.realname = res.data.nickname
        this.receiveUserInfo.avatar = res.data.avatar
        this.getMessage()
      })
    }

    //监听键盘高度
    uni.onKeyboardHeightChange((res) => {
      this.keyboardHeight = this.rpxTopx(res.height)
      if (this.keyboardHeight <= 0) {
        this.keyboardHeight = 0
        this.showMoreMenu = false
      }
    })
    //创建录音实例
    this.voice.recordInstance = uni.getRecorderManager()

    this.readedMsg()
  },
  methods: {
    //下拉刷新,分页用的
    topRefresh() {
      if (this.pageNum < this.returnPageNum) {
        this.pageNum++
        this.judgeScrollToBottom = false
        this.loading = true
        //调用消息接口，拉去消息
        this.getMessage()
      }
    },

    //获取聊天消息
    getMessage() {
      const app = this
      let data = []
      this.im.history({
        id: app.toAccountid, //用户id或者群id
        type: app.$goEasy.IM_SCENE.PRIVATE, //群聊：GoEasy.IM_SCENE.GROUP, 客服：GoEasy.IM_SCENE.CS,
        lastTimestamp: null, //上次查询结果里最后一条消息的时间戳，首次查询传入null即可
        limit: 30, //可选项，返回的消息条数，默认为10条，最多30条
        onSuccess: function (result) {
          console.debug('Query history successfully, result:\n ' + JSON.stringify(result))
          if (result.content && result.content.length > 0) {
            result.content.forEach((msg, index) => {
              msg.isShowTime = false //时间显示打标
              if (index == 0) {
                msg.isShowTime = true
              }
              msg.sendTime = timeMethod.myTimeToLocal(msg.timestamp)
              app.msgID++ //消息id计数，定位消息list的索引
              if (app.startTime != '') {
                //第一条消息前面没时间，排出掉
                if (
                  Math.abs(timeMethod.calculateTime(msg.sendTime, app.startTime)) / 1000 >
                  app.msgConf.showTimeSpace
                ) {
                  //计算消息时间间隔大于120秒
                  msg.isShowTime = true //注入打标数据
                }
              }
              app.startTime = msg.sendTime //每次循环记住该条消息时间，用于计算消息之间时间间隔
              // app.msgList.unshift(e); //处理好数据后push进消息list
              // console.log('app.startTime', app.startTime)
              let wxUser = {
                nickName: app.userName,
                headImg: app.userAvatar
              }
              if (app.senderId != msg.senderId) {
                wxUser.nickName = app.receiveUserInfo.realname
                wxUser.headImg = app.receiveUserInfo.avatar
              }

              let content = ''
              try {
                let text = JSON.parse(msg.payload.text)
                content = text.content
              } catch (error) {
                content = msg.payload.text
              }

              // console.log('wxUser',wxUser,app.userName)
              app.msgList.push({
                id: msg.messageId,
                senderId: msg.senderId,
                acceptUserId: msg.receiverId,
                type: msg.type,
                content: content,
                sendTime: msg.sendTime,
                isShowTime: msg.isShowTime,
                wxUser: wxUser
              })
            })
          }
        },
        onFailed: function (error) {
          //获取失败
          console.log(
            'Failed to query private message, code:' + error.code + ' content:' + error.content
          )
        }
      })

      this.showMsgTime(data)
      this.loading = false
      //})
    },

    //消息时间展示
    showMsgTime(data) {
      let newData = []
      const app = this
      app.msgList.forEach((e) => {
        e.isShowTime = false //时间显示打标
        e.sendTime = timeMethod.myTimeToLocal(e.sendTime)
        this.msgID++ //消息id计数，定位消息list的索引
        if (this.startTime != '') {
          //第一条消息前面没时间，排出掉
          if (
            Math.abs(timeMethod.calculateTime(e.sendTime, this.startTime)) / 1000 >
            this.msgConf.showTimeSpace
          ) {
            //计算消息时间间隔大于120秒
            this.msgList.slice(0 - this.msgID)[0].isShowTime = true //注入打标数据
          }
        }
        this.startTime = e.sendTime //每次循环记住该条消息时间，用于计算消息之间时间间隔
        this.msgList.unshift(e) //处理好数据后push进消息list
      })
      //消息列表最上面一条显示时间
      if (this.pageNum == this.returnPageNum) {
        this.msgList[0].isShowTime = true
      }
    },

    //时间转变
    changeTime(time) {
      let space =
        (new Date(timeMethod.myTimeToLocal(time)) -
          new Date(timeMethod.getNowTime().split('T')[0] + 'T00:00:00')) /
        (1000 * 60 * 60 * 24)
      let Time = timeMethod.myTimeToLocal(time).split(' ')
      let week = timeMethod.getDateToWeek(time)

      //当天
      if (space > 0 && space < 1) {
        return Time[1].slice(0, 5)
      }
      //昨天
      else if (space > -1 && space < 0) {
        return '昨天 ' + Time[1].slice(0, 5)
      }
      //星期
      else if (
        space < -1 &&
        Math.abs(space) < timeMethod.getDateToWeek(timeMethod.getNowTime()).weekID - 1
      ) {
        return week.weekName + ' ' + Time[1].slice(0, 5)
      }
      //日期
      else {
        return Time[0].slice(5, 10) + ' ' + Time[1].slice(0, 5)
      }
    },

    //输入框聚焦
    focus() {
      this.scrollToBottom()
    },

    //输入框取消聚焦
    blur() {
      this.scrollToBottom()
    },

    // px转换成rpx
    rpxTopx(px) {
      let deviceWidth = uni.getSystemInfoSync().windowWidth
      let rpx = (750 / deviceWidth) * Number(px)
      return Math.floor(rpx)
    },

    // 监视聊天发送栏高度
    sendHeight() {
      setTimeout(() => {
        let query = uni.createSelectorQuery()
        query.select('.send-msg').boundingClientRect()
        query.exec((res) => {
          this.bottomHeight = this.rpxTopx(res[0].height)
        })
      }, 200)
    },

    // 滚动至聊天底部
    scrollToBottom(e) {
      setTimeout(() => {
        let query = uni.createSelectorQuery().in(this)
        query.select('#scrollview').boundingClientRect()
        query.select('#msglistview').boundingClientRect()
        query.exec((res) => {
          if (res[1].height > res[0].height) {
            this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
          }
        })
      }, 200)
    },

    // 发送消息
    handleSend(e, f) {
      this.judgeScrollToBottom = true
      this.pageNum = 1
      const app = this
      //如果消息不为空
      let type = 101,
        type1 = 'text'
      if (e == 1) {
        type = 101
        type1 = 'text'
      } else if (e == 2) {
        type = 102
        type1 = 'img'
      } else if (e == 3) {
        type = 103
        type1 = 'voice'
      } else if (e == 4) {
        type = 104
        type1 = 'video'
      }
      if (e == 1 && this.chatMsg.length == 0) {
        return
      }
      if (e == 2) {
        app.chatMsg = f
      }

      let msg = {
        content: app.chatMsg,
        receiveNickname: app.receiveUserInfo.realname,
        receiveAvatar: app.receiveUserInfo.avatar,
        toShopId: app.toShopId,
        shopUserId: app.shopUserId
      }

      let textMessage = this.im.createTextMessage({
        text: JSON.stringify(msg), //消息内容
        to: {
          type: app.$goEasy.IM_SCENE.PRIVATE, //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
          id: `${app.toAccountid}`, //接收方用户id
          data: {
            nickname: `${app.realName}`,
            avatar: `${app.userAvatar}`,
            isShop: app.shopId,
            type: type1
          } //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
        }
      })

      //发送消息
      this.im.sendMessage({
        message: textMessage,
        onSuccess: function (message) {
          //发送成功

          //为了回显的
          app.msgList.push({
            id: 30,
            senderId: app.senderId,
            acceptUserId: app.toAccountid,
            type: type1,
            content: e == 1 ? app.chatMsg : f,
            interview: type1 == 'invite' ? JSON.parse(f) : '',
            sendTime: message.timestamp,
            wxUser: {
              nickName: app.realName,
              headImg: app.userAvatar,
              postId: app.postId
            }
          })
          app.chatMsg = ''
        },
        onFailed: function (error) {
          //发送失败
          console.log(
            'Failed to send private message，code:' + error.code + ' ,error ' + error.content
          )
        }
      })
    },

    //接收消息或发送消息时间显示
    showTime() {
      let time = timeMethod.getNowTime()
      if (
        timeMethod.calculateTime(time, this.msgList.slice(-1)[0].sendTime) / 1000 >
        this.msgConf.showTimeSpace
      ) {
        return true
      } else {
        return false
      }
    },

    //已读消息
    readedMsg() {},

    //语音播放
    playSound(url) {
      console.log(url)
      this.imgConf.replayChange = this.imgConf.replaing
      let music = null
      music = uni.createInnerAudioContext()
      music.src = url
      music.play()
      console.log('阅读完毕')
      music.onEnded(() => {
        console.log('阅读完毕2')
        music = null
        this.imgConf.replayChange = this.imgConf.replay
      })
    },

    //msglist索引-删除消息list中的元素
    cancelMsg(id) {
      //自定义的移除list元素的方法
      Array.prototype.remove = function (dx) {
        if (isNaN(dx) || dx > this.length) {
          return false
        }
        for (var i = 0, n = 0; i < this.length; i++) {
          if (this[i] != this[dx]) {
            this[n++] = this[i]
          }
        }
        this.length -= 1
      }
      //直接调用移除消息list中的元素
      this.msgList.remove(id)
    },

    //语音图标切换
    changeInputType() {
      if (this.changeLogUrl == this.imgConf.speak) {
        this.changeLogUrl = this.imgConf.keyboard
        this.textareaConf.disabled = true
        this.textareaConf.text = '按住说话'
        this.chatMsg = ''
      } else {
        this.changeLogUrl = this.imgConf.speak
        this.textareaConf.disabled = false
        this.textareaConf.text = ''
      }
    },

    //全局点击关闭
    touchClose() {
      this.showBoxId = ''
      this.showMoreMenu = false
      this.keyboardHeight = 0
    },

    //更多菜单
    moreMenu() {
      setTimeout(() => {
        this.keyboardHeight = 300
        this.showMoreMenu = true
      }, 200)
    },

    // 开始录制语音
    handleTouchStart(e) {
      var that = this
      if (this.textareaConf.disabled) {
        that.voice.finished = false //手指离开按钮打标
        console.log(11122)
        // #ifdef MP
        uni.getSetting({
          success(res) {
            if (res.authSetting['scope.record'] === undefined) {
              console.log('第一次授权')
            } else if (!res.authSetting['scope.record']) {
              uni.showToast({
                icon: 'none',
                title: '点击右上角···进入设置开启麦克风授权！',
                duration: 2000
              })
            } else {
              that.voice.recordInstance.start()
              that.voice.mask = true
              that.voice.isRecord = true
              that.voice.length = 1
              that.voice.startX = e.touches[0].pageX
              that.voice.startY = e.touches[0].pageY
              that.voice.timer = setInterval(() => {
                that.voice.length += 1
                if (that.voice.length >= 60) {
                  clearInterval(that.voice.timer)
                  that.handleTouchEnd()
                }
              }, 1000)
              //判断先结束按钮但是录制才开始时不会结束录制的条件；因为获取授权这儿存在延时；所以结束录制时可能还没开始录制
              if (that.voice.finished && that.voice.mask) {
                that.handleTouchEnd()
              }
            }
          }
        })
        // #endif

        // #ifdef APP
        if (uni.getStorageSync('audioPer')) {
          that.voice.recordInstance.start()
          that.voice.mask = true
          that.voice.isRecord = true
          that.voice.length = 1
          that.voice.startX = e.touches[0].pageX
          that.voice.startY = e.touches[0].pageY
          that.voice.timer = setInterval(() => {
            that.voice.length += 1
            if (that.voice.length >= 60) {
              clearInterval(that.voice.timer)
              that.handleTouchEnd()
            }
          }, 1000)
          //判断先结束按钮但是录制才开始时不会结束录制的条件；因为获取授权这儿存在延时；所以结束录制时可能还没开始录制
          if (that.voice.finished && that.voice.mask) {
            that.handleTouchEnd()
          }
          return
        }

        permision.androidPermissionCheck(['android.permission.RECORD_AUDIO']).then((res) => {
          if (res == 1) {
            uni.setStorageSync('audioPer', true)
          } else if (res == 0) {
            uni.setStorageSync('audioPer', true)
            uni.dialog.confirm(
              '录音权限说明',
              '，发送聊天语音需要手机录音权限，请您确认授权，否则无法使用该功能。',
              () => {}
            )
          } else {
            uni.dialog.confirm(
              '录音权限说明',
              '您已关闭手机录音权限，发送聊天语音需要手机录音权限，请您手动开启授权，否则无法使用该功能。',
              () => {}
            )
          }
        })

        // #endif
      }
    },

    // 语音录制时滑动事件
    handleTouchMove(e) {
      if (this.textareaConf.disabled) {
        if (this.voice.startY - e.touches[0].pageY > 100) {
          this.voice.cancel = true
        } else {
          this.voice.cancel = false
        }
      }
    },

    // 语音录制结束
    handleTouchEnd() {
      console.log('ennnn')
      if (this.textareaConf.disabled) {
        console.log(888)

        this.voice.finished = true
        this.voice.mask = false
        clearInterval(this.voice.timer)
        this.voice.recordInstance.stop()

        console.log(this.voice.recordInstance)
        this.voice.recordInstance.onStop((res) => {
          console.log(999)
          console.log(res.tempFilePath)
          const message = {
            voice: res.tempFilePath,
            length: this.voice.length
          }
          if (!this.voice.cancel) {
            console.log(100101)
            if (this.voice.length > 1) {
              console.log('uuuupp')
              uploadFiles(message.voice).then((res) => {
                this.handleSend(3, res.data)
              })
            } else {
              uni.showToast({
                icon: 'none',
                title: '语音时间太短',
                duration: 1000
              })
            }
          } else {
            this.voice.cancel = false
          }
        })
      }
    },

    //发送文件
    sendFile(type, data) {
      var that = this
      if (type == 'choose') {
        uni.chooseImage({
          count: 1,
          sourceType: ['album'],
          success: (res) => {
            console.log('img')
            console.log(res)

            uploadFiles(res.tempFilePaths[0]).then((res) => {
              console.log('resss', res)
              this.handleSend(2, res.data)
            })
          }
        })
      } else if (type == 'shoot') {
        uni.chooseVideo({
          count: 1,
          mediaType: ['video'],
          success: (res) => {
            uploadFiles(res.tempFilePath).then((res) => {
              console.log(4444, res.data)
              this.handleSend(4, res.data)
            })
          },
          fail: (err) => {
            console.log(err)
          }
        })
      } else {
        //that.uploadFile(data.voice, 'voice')
        console.log(data.voice)
        uploadFiles(data.voice).then((res) => {})
      }
    },
    playVideo(e) {
      uni.navigateTo({
        url: '/other/video-play/video-play?&play=' + e.content
      })
    }

    // uploadFile(path, type) {
    // 	var that = this;
    // 	let data = {
    // 		"senderId": this.userId,
    // 		"acceptUserId": this.toUserId,
    // 		"type": type
    // 	};
    // 	if (type == 'voice') {
    // 		data = {
    // 			"senderId": this.userId,
    // 			"acceptUserId": this.toUserId,
    // 			"type": type,
    // 			"time": this.voice.length
    // 		};
    // 	}
    // 	uni.uploadFile({
    // 		url: '接口地址',
    // 		filePath: path,
    // 		name: 'file',
    // 		formData: data,
    // 		header: {
    // 			"token": this.$store.state.token
    // 		},
    // 		success: res =>  {
    // 			let newMsg = JSON.parse(res.data)
    // 			//上传成功后，接口会返回消息数据 格式与上方的消息时一样的，然后把返回的数据push到消息list中
    // 			that.msgList.push(newMsg.data)
    // 		}
    // 	})
    // }
  }
}
</script>
<style scoped lang="scss">
$chatContentbgc: #c2dcff;
$sendBtnbgc: #4f7df5;

center {
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 聊天消息 */
.chat {
  .topTabbar {
    width: 100%;
    height: 90rpx;
    line-height: 90rpx;
    display: flex;
    margin-top: 80rpx;
    justify-content: space-between;

    .icon {
      margin-left: 20rpx;
    }

    .text {
      margin: auto;
      font-size: 16px;
      font-weight: 700;
    }

    .button {
      width: 10%;
      margin: auto 20rpx auto 0rpx;
    }
  }

  .scroll-view {
    ::-webkit-scrollbar {
      display: none;
      width: 0 !important;
      height: 0 !important;
      -webkit-appearance: none;
      background: transparent;
      color: transparent;
      z-index: 0;
    }

    background-color: #f6f6f6;

    .chat-body {
      display: flex;
      flex-direction: column;
      padding-top: 23rpx;

      .self {
        justify-content: flex-end;
        position: relative;
      }

      .Ai {
        position: relative;
      }

      .item {
        display: flex;
        padding: 23rpx 30rpx;

        .right {
          background-color: $chatContentbgc;
        }

        .left {
          background-color: #ffffff;
        }

        .right::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          left: 100%;
          top: 10px;
          border: 12rpx solid transparent;
          border-left: 12rpx solid $chatContentbgc;
        }

        .left::after {
          position: absolute;
          display: inline-block;
          content: '';
          width: 0;
          height: 0;
          top: 10px;
          right: 100%;
          border: 12rpx solid transparent;
          border-right: 12rpx solid #ffffff;
        }

        .content-text {
          position: relative;
          max-width: 486rpx;
          border-radius: 8rpx;
          word-wrap: break-word;
          padding: 24rpx 24rpx;
          margin: 0 24rpx;
          border-radius: 5px;
          font-size: 32rpx;
          font-family: PingFang SC;
          font-weight: 500;
          color: #333333;
          line-height: 42rpx;
        }

        .content-img {
          margin: 0 24rpx;
        }

        .content-video {
          margin: 0 24rpx;
        }

        .img-style {
          width: 400rpx;
          height: auto;
          border-radius: 10rpx;
        }

        .video-style {
          width: 400rpx;
          height: 400rpx;
        }

        .avatar {
          display: flex;
          justify-content: center;
          width: 78rpx;
          height: 78rpx;
          background: $sendBtnbgc;
          border-radius: 50rpx;
          overflow: hidden;

          image {
            align-self: center;
          }
        }

        .msg-menu {
          min-width: 100rpx;
          height: 100rpx;
          display: none;
          background: #383838;
          position: absolute;
          border-radius: 10rpx;
          z-index: 100;

          .tr-icon {
            position: absolute;
            top: 100rpx;
            width: 0;
            height: 0;
            border: 15rpx solid transparent;
            border-top: 15rpx solid #383838;
          }

          .tr-icon-left {
            left: 15rpx;
          }

          .tr-icon-right {
            right: 15rpx;
          }
        }

        .menu-left {
          top: -100rpx;
          left: 120rpx;
        }

        .menu-right {
          top: -100rpx;
          right: 120rpx;
        }
      }
    }

    .msg-time {
      font-size: 24rpx;
      text-align: center;
      color: #737373;
    }
  }

  .chat-bottom {
    width: 100%;
    height: auto;
    background: #f4f5f7;
    transition: all 0.25s ease;

    .send-msg {
      display: flex;
      align-items: flex-end;
      padding: 16rpx 15rpx;
      width: 100%;
      min-height: 130rpx;
      position: fixed;
      bottom: 0;
      background: #fff;
      transition: all 0.25s ease;

      .uni-textarea {
        width: 100%;
        padding-bottom: 40rpx;
        display: flex;
        align-items: center;

        .icon-style {
          width: 50rpx;
          height: 50rpx;
          margin: 0 20rpx;
        }

        .out_textarea_box {
          flex: 1;
          min-height: 80rpx;
          max-height: 200rpx;
          border-radius: 8rpx;
          background: #f1f1f1;
          display: flex;
          justify-content: center;
          align-items: center;

          textarea {
            width: 98%;
            min-height: 42rpx;
            max-height: 200rpx;
            background: #f1f1f1;
            font-size: 32rpx;
            font-family: PingFang SC;
            color: #333333;
          }
        }
      }
    }
  }

  .more-menu {
    width: 100%;
    min-height: 300rpx;
    margin-top: 150rpx;
    display: none;
    position: fixed;
    bottom: 0;
    background: #fff;

    .inner-box {
      width: 98%;
      height: 280rpx;
      margin: 10rpx 1%;
      display: flex;

      .menu {
        width: 120rpx;
        height: 130rpx;
        background: #eee;
        margin: 20rpx;
        border-radius: 20rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .i-style {
          width: 80rpx;
          height: 80rpx;
        }

        .t-style {
          font-size: 22rpx;
          font-weight: 600;
          text-align: center;
        }
      }
    }
  }

  .voice-mask {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.8);

    .inner-mask {
      display: flex;
      flex-direction: column;
      align-items: center;

      .voice-progress-box {
        min-width: 250rpx;
        height: 150rpx;
        margin-top: 60%;
        border-radius: 50rpx;
        background: #4df861;
        position: relative;
        @extend center;

        .third-icon {
          width: 0;
          height: 0;
          border: 15rpx solid transparent;
          border-top: 15rpx solid #4df861;
          position: absolute;
          top: 100%;
          left: 45%;
        }

        .progress-num {
          font-size: 50rpx;
          font-weight: 600;
        }
      }

      .cancel-btn {
        width: 120rpx;
        height: 120rpx;
        clip-path: circle();
        margin-top: 50%;
        background: #080808;
        @extend center;
      }

      .cancelBtn {
        width: 150rpx;
        height: 150rpx;
      }

      .show-tips {
        width: 100%;
        margin-top: 80rpx;
        text-align: center;
        color: white;
        animation: 4s opacity2 1s infinite;
        font-size: 30rpx;
        font-weight: 400;
        font-family: sans-serif;
      }

      @keyframes opacity2 {
        0% {
          opacity: 0;
        }

        50% {
          opacity: 0.8;
        }

        100% {
          opacity: 0;
        }
      }

      .bottom-area {
        position: fixed;
        bottom: 0rpx;
        width: 100%;
        height: 190rpx;
        border-top: #bababb 8rpx solid;
        border-radius: 300rpx 300rpx 0 0;
        background-image: linear-gradient(#949794, #e1e3e1);
        @extend center;

        .img-style {
          width: 50rpx;
          height: 50rpx;
        }
      }
    }
  }
}

view,
button,
text,
input,
textarea {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

//去除scroll-view的滑动条
::-webkit-scrollbar {
  display: none;
  width: 0 !important;
  height: 0 !important;
  -webkit-appearance: none;
  background: transparent;
}

.sendBtn {
  width: 120rpx;
  height: 60rpx;
  border-radius: 10rpx;
  text-align: center;
  background-color: #4f7df5;
  line-height: 60rpx;
  font-size: 24rpx;
  color: #fff;
  margin-left: 15rpx;
}

.swiper {
  width: 750rpx;
  height: 600rpx;
  position: fixed;
  bottom: 0;

  .icon {
    font-size: 48rpx;
    margin: 10rpx;
  }
}

.slider-emoji {
  display: flex;
  flex-wrap: wrap;
}
</style>
